package com.poi.demopoi.controller2;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.function.Consumer;

/**
 * @Author: yh
 * @Description:
 * @Date: Created in 9:44  2018/6/29.
 * @Modified By:
 */

public class Util {
    /**
     * 分批操作list，无返回值
     *
     * @param list 需要插入数据库的数据
     * @param consumer jav8函数接口
     * @param <T>
     */
    public static <T> Integer sublist(List<T> list, Consumer<List<T>> consumer) {
        //多少分多少条插入
        return sublist(list, consumer, 5000);
    }

    public static <T> Integer sublist(List<T> list, Consumer<List<T>> consumer, int pageSize) {
        Integer count = 0;
        if (list.size() == 0) {
            return count;
        }
        if (list.size() < pageSize) {
            consumer.accept(list);
            count = list.size();
        } else {
            int page = list.size() / pageSize;
            int lave = list.size() % pageSize;
            page = (lave != 0) ? page + 1 : page;
            for (int i = 1; i <= page; i++) {
                int start = (i-1) * (pageSize);
                int end = (i == page) ? start+lave : pageSize+start;
                List<T> current = list.subList(start, end);
                consumer.accept(current);
                count = end;
            }
        }
        return count;
    }
}
